package com.wuwangfu.window.process;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * @Author jcshen
 * @Date 2023-02-23
 * @PackageName:com.wuwangfu.window
 * @ClassName: ProcessTimeTumbleWindowAll
 * @Description:
 * @Version 1.0.0
 *
 *  https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/dev/datastream/operators/windows/#tumbling-windows
 *
 * 不分组，按照processingTime划分滚动窗口
 *
 */
public class ProcessTimeTumbleWindowAll {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        /*旧API想要指定时间类型，新API不需要指定*/
//        env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);

        DataStreamSource<String> line = env.socketTextStream("localhost", 8888);
        SingleOutputStreamOperator<Tuple2<String, Integer>> maped = line.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                String[] fields = value.split(",");
                return Tuple2.of(fields[0], Integer.valueOf(fields[1]));
            }
        });
        /*不keyBy，只有1个并行度，按所在机器的processingTime划分窗口（通过web ui可以看出）*/
        //默认是ProcessingTime（处理时间，当前机器时间），TumblingProcessingTimeWindows（滚动窗口）
//        AllWindowedStream<Integer, TimeWindow> windowed = maped.timeWindowAll(Time.seconds(5));
//        windowed.sum(1).print();
        /*-------------------------新API---------------------------------*/
        //调用keyBy
        KeyedStream<Tuple2<String, Integer>, String> keyed = maped.keyBy(t -> t.f0);
        /**
         * ctrl+alt 查看 WindowAssigner
         *
         * NonKeyd Window：不调用keyBy，然后调用windowAll方法，传入windowAssinger
         * Keyd Window：先调用keyBy，然后调用window方法，传入windowAssinger
         */
        AllWindowedStream<Tuple2<String, Integer>, TimeWindow> windowed = maped.windowAll(TumblingProcessingTimeWindows.of(Time.seconds(5)));
        //windowed.sum(1).print();

        windowed.reduce(new ReduceFunction<Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> reduce(Tuple2<String, Integer> v1, Tuple2<String, Integer> v2) throws Exception {
                //增量聚合
                v1.f1 = v1.f1 + v2.f1;
                return v1;
            }
        }).print();


        env.execute();
    }
}
